package com.jingbian.cppccbackend.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jingbian.cppccbackend.entity.*;
import com.jingbian.cppccbackend.entity.dto.PublicOpinionSignersListDTO;
import com.jingbian.cppccbackend.mapper.user.PublicOpinionAttachmentsMapper;
import com.jingbian.cppccbackend.mapper.user.PublicOpinionSignersMapper;
import com.jingbian.cppccbackend.mapper.user.PublicOpinionsMapper;
import com.jingbian.cppccbackend.service.user.PublicOpinionSignersService;
import com.jingbian.cppccbackend.service.user.PublicOpinionsService;
import com.jingbian.cppccbackend.utils.ThreadLocalUtil;
import com.jingbian.cppccbackend.vo.PublicOpinionSignersListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class PublicOpinionSignersServiceImpl extends ServiceImpl<PublicOpinionSignersMapper, PublicOpinionSigners> implements PublicOpinionSignersService {

    @Autowired
    private PublicOpinionSignersMapper publicOpinionSignersMapper;
    @Autowired
    private PublicOpinionsMapper publicOpinionsMapper;
    @Autowired
    private PublicOpinionAttachmentsMapper publicOpinionAttachmentsMapper;

    @Override
    public PageInfo<PublicOpinionSignersListVO> getList(PublicOpinionSignersListDTO publicOpinionSignersListDTO) {
        // 开启分页
        PageHelper.startPage(publicOpinionSignersListDTO.getPageNum(), publicOpinionSignersListDTO.getPageSize());

        // 获取当前用户ID
        Map<String, Object> claims = ThreadLocalUtil.get();
        publicOpinionSignersListDTO.setUserId((Integer) claims.get("uid"));

        // 执行查询
        List<PublicOpinionSignersListVO> list = publicOpinionSignersMapper.getSignerList(publicOpinionSignersListDTO);

        // 返回分页结果
        return new PageInfo<>(list);
    }

    @Override
    public PublicOpinionSigners changeStatus(Integer oid, String status) {
        /**
         * 1.获取ThreadLocal中的用户Id
         */
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("uid");
        /**
         * 2.对联名表的操作进行处理
         */
        UpdateWrapper<PublicOpinionSigners> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("public_opinion_id", oid)
                .eq("user_id", userId);
        updateWrapper.set("dispose_status", status);
        publicOpinionSignersMapper.update(null, updateWrapper);

        /**
         * 3.查询联名表是否有未处理的用户，根据有无进行不同的操作。
         */
        LambdaQueryWrapper<PublicOpinionSigners> selectWrapper = new LambdaQueryWrapper<>();
        selectWrapper.eq(PublicOpinionSigners::getPublicOpinionId,oid).eq(PublicOpinionSigners::getDisposeStatus,"未处理");
        // 执行查询
        List<PublicOpinionSigners> signers = publicOpinionSignersMapper.selectList(selectWrapper);

        /**
         * 3.1 如果用户进行的是同意操作，并且联名表所有的用户都操作完了，则将isOr设置为true
         */
        if (signers.isEmpty()&&!status.equals("拒绝")) {
            System.out.println("执行true");
            LambdaUpdateWrapper<PublicOpinions> updateWrapper1 = new LambdaUpdateWrapper<>();
            updateWrapper1
                    .set(PublicOpinions::getIsOr, true)
                    .set(PublicOpinions::getIsOrTime, LocalDateTime.now()) // 设置联名通过时间为当前时间
                    .eq(PublicOpinions::getOpinionId, oid)
                    .and(wrapper -> wrapper
                            .ne(PublicOpinions::getIsOr, false)
                            .or()
                            .isNull(PublicOpinions::getIsOr)
                    );
            // 执行更新，并返回受影响的行数
            publicOpinionsMapper.update(null, updateWrapper1);
        }
        /**
         * 3.2 如果用户执行的是拒绝操作，则将isOr设为false。
         */
        if (status.equals("拒绝")){
            LambdaUpdateWrapper<PublicOpinions> updateWrapper1 = new LambdaUpdateWrapper<>();
            updateWrapper1
                    .set(PublicOpinions::getIsOr, false)          // 设置 isOr = true
                    .eq(PublicOpinions::getOpinionId,oid);               // 限定当前提案ID对应的记录
            // 执行更新，并返回受影响的行数
            publicOpinionsMapper.update(null, updateWrapper1);
        }
        /**
         * 4.进行查询，返回用户所操作的状态。
         */
        LambdaQueryWrapper<PublicOpinionSigners> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PublicOpinionSigners::getPublicOpinionId, oid)
                .eq(PublicOpinionSigners::getUserId, userId);
        return publicOpinionSignersMapper.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public Integer deleteConsignOpinion(Integer opinionId) {
        /**
         * 返回1，则表示提案不存在
         * 返回2，则表示与用户id不一致
         * 返回3，提案已过初审的申请
         * 返回4，提案删除成功！1
         */
        LambdaQueryWrapper<PublicOpinions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PublicOpinions::getOpinionId,opinionId);
        PublicOpinions publicOpinions = publicOpinionsMapper.selectOne(wrapper);
        if(publicOpinions == null) {
            return 1;
        }
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer uid = (Integer)claims.get("uid");
        if (!publicOpinions.getUserId().equals(uid)){
            return 2;
        }

        if ( Objects.nonNull(publicOpinions.getIsOr())&&publicOpinions.getIsOr()){
            return 3;
        }

        /**
         * 进行提案联名的联名人待处理或已处理的事项进行删除操作。
         */
        LambdaQueryWrapper<PublicOpinionSigners> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(PublicOpinionSigners::getPublicOpinionId, opinionId);
        publicOpinionSignersMapper.delete(wrapper1);
        /**
         *
         * 针对于附件表进行删除操作。
         */
        LambdaQueryWrapper<PublicOpinionAttachments> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(PublicOpinionAttachments::getPublicOpinionId, opinionId);
        publicOpinionAttachmentsMapper.delete(wrapper2);
        /**
         * 对于提案表进行删除操作。
         */
        publicOpinionsMapper.delete(wrapper);
        return 4;
    }
}
